//创建连接
var conn = new WebIM.connection({
    https: WebIM.config.https,
    url: WebIM.config.xmppURL,
    isAutoLogin: WebIM.config.isAutoLogin,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions
});


/**
 * 获取好友列表
 */
var getFriends = function () {
    conn.getRoster({
        success: function ( roster ) {
            console.log(roster);

            //获取好友列表，并进行好友列表渲染，roster格式为：
            /** [
                 {
                   jid:'asemoemo#chatdemoui_test1@easemob.com',
                   name:'test1',
                   subscription: 'both'
                 }
                ]
             */
            $(".friendsList").empty();
            for ( var i = 0, l = roster.length; i < l; i++ ) {
                var ros = roster[i];
                //ros.subscription值为both/to为要显示的联系人，此处与APP需保持一致，才能保证两个客户端登录后的好友列表一致
                if ( ros.subscription === 'both' || ros.subscription === 'to' ) {
                    $(".friendsList").append("<li>" + ros.name + "</li>");
                }
            }
        }
    });
};


/**
 * 注册环信账号
 * @param username 用户名
 * @param password 密码
 * @param nickname 昵称
 */
var hxRegister = function(username,password,nickname,success){
    var options = {
        username: username,
        password: password,
        nickname: nickname,
        appKey: WebIM.config.appkey,
        success: success,
        error: function () { },
        apiUrl: WebIM.config.apiURL
    };
    conn.registerUser(options);
};


/**
 * 环信登陆
 * @param username 用户名
 * @param password 密码
 */
function hxLogin(username,password,success){
    if(username && password){
        console.log("token不存在~");
        var options = {
            apiUrl: WebIM.config.apiURL,
            user: username,
            pwd: password,
            appKey: WebIM.config.appkey,
            success: success,
            error: function(data){
				console.log("错误");
            }
        };
        conn.open(options);
    }else{
        var token = WebIM.utils.getCookie(hex_sha1(username));
        var hex_username = "webim_" + hex_sha1(username);
        if(isEmptyObject(token) == false){
            var options = {
                apiUrl: WebIM.config.apiURL,
                user: username,
                accessToken: token[hex_username],
                appKey: WebIM.config.appkey,
                success: success,
                error: function(data){

                }
            };
            conn.open(options);
        }else{
            alert('用户或密码未输入完整');
        }
    }
}


/**
 * token登录
 * @param token
 */
var hxTokenLogin = function (token) {
    var options = {
        apiUrl: WebIM.config.apiURL,
        accessToken: token,
        appKey: WebIM.config.appkey
    };
    conn.open(options);
}


/**
 * 退出
 */
function hxUserExit() {
    console.log("退出成功~");
    removeSessionAll();
    conn.close();
}


/**
 * 添加好友
 * @param toUsername 要添加的好友用户名
 */
var addFriends = function (obj) {
    console.log($(obj).parents('form').find("input[name='username']").val());
    conn.subscribe({
        to: $(obj).parents('form').find("input[name='username']").val(),
        // Demo里面接收方没有展现出来这个message，在status字段里面
        message: '加个好友呗!'
    });
};

//收到联系人订阅请求的处理方法，具体的type值所对应的值请参考xmpp协议规范
var handlePresence = function ( e ) {

};


/**
 * 单聊发送文本消息
 * @param to 发送到指定的用户
 * @param message 消息内容
 */
var sendPrivateText = function (to,message,success) {

    var id = conn.getUniqueId();                 // 生成本地消息id
    var msg = new WebIM.message('txt', id);      // 创建文本消息
    msg.set({
        msg: message,                  // 消息内容
        to: to,                          // 接收消息对象（用户id）
        ext:{"name":"单聊","age":25},// 自定义属性
        roomType: false,
        success: success
    });
    msg.body.chatType = 'singleChat';
    console.log(msg);
    conn.send(msg.body);
};


// 查询群组成员
// 查询出来的member的结构为{affiliation: 'member', jid: 'easemob-demo#chatdemoui_wjy6@easemob.com'}
// 注意，这里的jid格式，成员的用户名是chatdemoui_之后，@easemob.com之前的字符串，如本例的wjy6是用户名
var queryRoomMember = function (roomId,success) {
    var member = '';
    conn.queryRoomMember({
        roomId: roomId,
        success: success
    });
};


// 获取群组信息
var hxQueryGroupInfo = function (roomId) {
    console.log(roomId);

    conn.queryRoomInfo({
        roomId: roomId,
        // settings 表示入群的权限，具体值待定
        // members[0]里面包含群主信息，其结构为{affiliation: 'owner', jid: appKey + '_' + username + '@easemob.com'}
        // jid中的username就是群主ID
        // fields的结构为：
        /*
         {
         affiliations: '2',
         description: '12311231313',         // 群简介
         maxusers: '200',                    // 群最大成员容量
         name: '123',                        // 群名称
         occupants: '2',
         owner: 'easemob-demo#chatdemoui_mengyuanyuan'               // 群主jid
         }
         */
        success: function (settings, members, fields) {
            console.log('settings: ', settings);
            console.log('members: ', members);
            console.log('fields: ', fields);
        },
        error: function () {
            console.log('Error!');
        }
    });
};


/**
 * 修改群组信息
 */
var hxChangeGroupInfo = function (roomId,subject,description,success) {
    var option = {
        roomId: roomId,
        subject: subject,    // 群组名称
        description: description,  // 群组简介
        success: success
    };
    console.log(option);
    conn.changeGroupSubject(option);
};

/**
 * 建立一个群组
 * @param name 群名称
 * @param description 群简介
 * @param members 以数组的形式存储需要加群的好友ID
 */
var hxCreateGroup = function (name,des,member) {
    // var arr = new Array(2);
    // arr[0] = "oli";
    // arr[1] = "oli2";
    // arr[0] = "1133161018115126#chaishi_oli@easemob.com";
    // arr[1] = "1133161018115126#chaishi_oli2@easemob.com";
    // console.log(arr);

    var option = {
        subject: name,                         // 群名称
        description: des,         // 群简介
        members: member,               // 以数组的形式存储需要加群的好友ID
        optionsPublic: true,                        // 允许任何人加入
        optionsModerate: false,                     // 加入需审批
        optionsMembersOnly: false,                  // 不允许任何人主动加入
        optionsAllowInvites: false                  // 允许群人员邀请
    };
    console.log(option);
    conn.createGroup(option);
}


/**
 * 解散一个群组
 * @param reason 原因
 * @param roomId 群id
 * @param success
 */
var hxDestroyGroup = function (reason,roomId,success) {
    var option = {
        reason: reason,
        roomId: roomId,
        success: success
    };
    console.log(option);
    conn.destroyGroup(option);
};


/**
 * 成员主动退出群
 */
var hxLeaveGroup = function (to,roomId,callback) {
    var option = {
        to: to,
        roomId: roomId,
        success: callback,
        error: function () {
            console.log('Leave room faild');
        }
    };
    conn.leaveGroupBySelf(option);
};


/**
 * 加好友入群
 * @param list 成员
 * @param roomId 群id
 */
var hxAddGroupMembers = function (list,roomId) {
    var option = {
        list: list,
        roomId: roomId
    };
    console.log(option);
    conn.addGroupMembers(option);
};


/**
 * 将成员踢出群(同将群成员拉入群黑名单)
 * @param roomId 群组ID
 * @param to 需要删除的成员ID
 * @param callback
 */
var hxAddToGroupBlackList = function (roomId,to,callback) {
    var option = {
        affiliation: 'owner',                       // 写死
        roomId: roomId,                    // 群组ID
        success: callback,
        to: to                               // 需要删除的成员ID
    };
    conn.addToGroupBlackList(option);
};


/**
 * 列出所有群组
 */
var listGroups = function (success) {
    var option = {
        success: success,
        error: function () {
            console.log('List groups error');
        }
    };
    conn.listRooms(option);
};


/**
 * 群组发送文本消息
 * @param to 发送的给群组里的每一个人
 * @param msg 消息
 * @param success
 */
var sendGroupText = function (type,to,message,success) {
    var id = conn.getUniqueId();            // 生成本地消息id
    var msg = new WebIM.message('txt', id); // 创建文本消息
    var option = {
        msg: message,             // 消息内容
        to: to,                     // 接收消息对象(群组id) 测试：1490753224149
        ext:{"name":"群组","age":100},
        roomType: false,
        chatType: type,                 //单聊为：chat，群聊为：groupchat，聊天室为：chatroom
        success: success,
        fail: function () {
            console.log('failed');
        }
    };
    msg.set(option);
    msg.setGroup('groupchat');
    conn.send(msg.body);
};

/**
 * 收到图片消息
 * @param message
 * @param success
 */
var hxPictureMessage = function (message,callback) {
    console.log('Picture');
    var options = {url: message.url};
    console.log("图片地址：" + message.url);

    options.onFileDownloadComplete = callback;//// 图片下载成功
    options.onFileDownloadError = function () {
        // 图片下载失败
        console.log('Image download failed!');
    };
    WebIM.utils.download.call(conn, options);
}


/**
 * 收到音频消息
 * @param message
 */
function hxAudioMessage(message,callback) {
    console.log(message);// 信息
    var options = { url: message.url,from:message.from };

    options.onFileDownloadComplete = callback;
    options.onFileDownloadError = function () {
        //音频下载失败
    };
    //通知服务器将音频转为mp3
    options.headers = {
        'Accept': 'audio/mp3'
    };
    WebIM.utils.download.call(conn, options);
}


/**
 * 单聊、群组发送图片消息
 * @param to 发送给指定的帐号
 * @param callback
 */
var hxSendPrivateImg = function (to,chat,callback) {
    var id = conn.getUniqueId();                   // 生成本地消息id
    var msg = new WebIM.message('img', id);        // 创建图片消息

    var input;
    if(chat == "singleChat"){// 【单聊】获取图片
        input = document.getElementById('singleImage');
    }else if(chat == "groupChat"){// 【群组】获取图片
        input = document.getElementById('groupImage');
    }

    var file = WebIM.utils.getFileUrl(input);      // 将图片转化为二进制文件
    var allowType = {
        'jpg': true,
        'gif': true,
        'png': true,
        'bmp': true
    }
    if (file.filetype.toLowerCase() in allowType) {
        var option = {
            apiUrl: WebIM.config.apiURL,
            file: file,
            to: to,                       // 接收消息对象
            roomType: false,
            chatType: chat,
            onFileUploadError: function () {      // 消息上传失败
                console.log('onFileUploadError');
            },
            onFileUploadComplete: function () {   // 消息上传成功
                console.log('onFileUploadComplete');
            },
            success: callback(file),
            flashUpload: WebIM.flashUpload
        };
        msg.set(option);
        console.log(msg.body);

        if(chat == "groupChat"){// 设置群组
            msg.setGroup('groupchat');
        }

        conn.send(msg.body);
    }
};


/**
 * 单聊、群组发送文件消息
 * @param to 发送给指定的帐号
 * @param callback
 */
var hxSendPrivateFile = function (to,chat,callback) {
    var id = conn.getUniqueId();                   // 生成本地消息id
    var msg = new WebIM.message('file', id);        // 创建文件消息

    var input;
    if(chat == "singleChat"){// 【单聊】获取文件
        input = document.getElementById('singleFile');
    }else if(chat == "groupChat"){// 【群组】获取文件
        input = document.getElementById('groupFile');
    }

    var file = WebIM.utils.getFileUrl(input);      // 将文件转化为二进制文件
    var allowType = {
        'jpg': true,
        'gif': true,
        'png': true,
        'bmp': true,
        'zip': true,
        'txt': true,
        'doc': true,
        'pdf': true
};
    if (file.filetype.toLowerCase() in allowType) {
        var option = {
            apiUrl: WebIM.config.apiURL,
            file: file,
            to: to,                       // 接收消息对象
            roomType: false,
            chatType: chat,
            onFileUploadError: function () {      // 消息上传失败
                console.log('onFileUploadError');
            },
            onFileUploadComplete: function () {   // 消息上传成功
                console.log('onFileUploadComplete');
            },
            success: callback(file),
            flashUpload: WebIM.flashUpload
        };
        msg.set(option);

        if(chat == "groupChat"){// 设置群组
            msg.setGroup('groupchat');
        }

        conn.send(msg.body);
    }
};


/**
 * 单聊发送音频消息
 * @param to 发送给指定的帐号
 * @param callback
 */
var hxSendPrivateAudio = function (to,chat,callback) {
    var id = conn.getUniqueId();                   // 生成本地消息id
    var msg = new WebIM.message('audio', id);      // 创建音频消息

    var input;
    if(chat == "singleChat"){// 【单聊】获取音频消息
        input = document.getElementById('singleAudio');
    }else if(chat == "groupChat"){// 【群组】获取音频消息
        input = document.getElementById('groupAudio');
    }

    var file = WebIM.utils.getFileUrl(input);      // 将音频转化为二进制文件
    var allowType = {
        'mp3': true,
        'amr': true,
        'wmv': true
    };
    if (file.filetype.toLowerCase() in allowType) {
        var option = {
            apiUrl: WebIM.config.apiURL,
            file: file,
            to: to,                       // 接收消息对象
            roomType: false,
            chatType: 'singleChat',
            onFileUploadError: function () {      // 消息上传失败
                console.log('onFileUploadError');
            },
            onFileUploadComplete: function () {   // 消息上传成功
                console.log('onFileUploadComplete');
            },
            success: callback(file),
            flashUpload: WebIM.flashUpload
        };
        msg.set(option);

        if(chat == "groupChat"){// 设置群组
            msg.setGroup('groupchat');
        }

        conn.send(msg.body);
    }
};



// 单聊发送视频消息
var hxSendPrivateVideo = function (to,chat,callback) {
    var id = conn.getUniqueId();                   // 生成本地消息id
    var msg = new WebIM.message('video', id);      // 创建视频消息

    var input;
    if(chat == "singleChat"){// 【单聊】获取视频
        input = document.getElementById('singleVideo');
    }else if(chat == "groupChat"){// 【群组】获取视频
        input = document.getElementById('groupVideo');
    }

    var file = WebIM.utils.getFileUrl(input);      // 将视频转化为二进制文件
    var allowType = {
        'mp4': true,
        'wmv': true,
        'avi': true,
        'rmvb':true,
        'mkv':true
    };
    if (file.filetype.toLowerCase() in allowType) {
        if(chat == "singleChat"){// 【单聊】
            var option = {
                apiUrl: WebIM.config.apiURL,
                file: file,
                to: to,                       // 接收消息对象
                roomType: false,
                chatType: chat,
                onFileUploadError: function () {      // 消息上传失败
                    console.log('onFileUploadError');
                },
                onFileUploadComplete: function () {   // 消息上传成功
                    console.log('onFileUploadComplete');
                },
                success: callback(file),
                flashUpload: WebIM.flashUpload
            };
        }else if(chat == "groupChat"){// 【群组】
            var option = {
                apiUrl: WebIM.config.apiURL,
                file: file,
                to: to,                       // 接收消息对象
                roomType: false,
                chatType: chat,
                group:"groupchat",
                onFileUploadError: function () {      // 消息上传失败
                    console.log('onFileUploadError');
                },
                onFileUploadComplete: function () {   // 消息上传成功
                    console.log('onFileUploadComplete');
                },
                success: callback(file),
                flashUpload: WebIM.flashUpload
            };
        }

        conn.send(option);
    }
};


/**
 * 删除好友
 * @param to 删除指定的好友
 * @param success
 */
var hxRemoveFriends = function (to,success) {
    conn.removeRoster({
        to: to,
        success: success,
        error: function () {    // 删除失败
        }
    });
};


/**
 * 获取黑名单列表
 */
var getBlackList = function () {
    conn.getBlacklist();
};


/**
 * 将好友加入黑名单
 * @param success
 */
var hxAddToBlackList = function (to,success) {
    // var list = getBlackList();
    console.log(conn.getBlacklist());

    // var session_black = getSessionStorage("session_black");
    // var eval_sub = eval("("+session_black+")");
    // alert(eval_sub.order);

    return;
    var list = {
        // sub_session_black,
        to: {
            jid: '1133161018115126#chaishi_'+to+'@easemob.com',
            name: to,
            subscription: 'both',
            order: to,
            type: 'jid'
        }
    };
    conn.addToBlackList({
        list: list,
        type: 'jid',
        success: success,
        error: function () {
            console.log('Add friend to black list error');
        }
    });
}
















/**
 *
 * @param key 设置存入值的名字
 * @param value 要缓存的参数
 */
function saveSessionStorage(key, value) {     /* 临时保存 */
    sessionStorage.setItem(key, value);
}
function getSessionStorage(key) {
    return sessionStorage.getItem(key);     /* 获取指定 */
}
function removeSessionStorage(key) {         /* 删除指定 */
    sessionStorage.removeItem(key);
}
function removeSessionAll() {                /* 删除所有 */
    sessionStorage.clear();
}
function lenSession() {                        /* 共有多少个sessionStorage */
    alert(sessionStorage.length);
}

/**
 * 判断是否为空的object
 * @param obj
 * @returns {boolean}
 */
function isEmptyObject(obj) {
    for (var key in obj) {
        return false;
    }
    return true;
}


